<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>扫码订单</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/admin.css">
    <link rel="stylesheet" href="/css/template.css">
    <link rel="stylesheet" href="/assets/bootstrap-3.3.5/css/bootstrap.css">
    <style>
        .layui-form-label {
            width: auto;
        }

        body {
            background-color: #f2f2f2
        }

        .layui-input-block {
            margin-left: 0px;
        }

        #goodsOrderDetailHead {
            height: auto;
            font-size: 15px;
        }
    </style>
</head>
<body>
<div style="padding: 15px">
    <div class="layui-form" id="" style="background-color: #f2f2f2;margin-top:16px">
        <div class="layui-form-item">
            <label class="layui-form-label" style="font-size: 20px;font-weight: bolder">扫码添加订单</label>
            <button class="layui-btn layui-btn-radius" lay-filter="option" id="add">添加
            </button>
            <button class="layui-btn layui-btn-radius" lay-filter="option" id="addAddress">添加地址
            </button>
            <button class="layui-btn layui-btn-radius layui-btn-normal" lay-filter="option" id="addOrder">确认订单
            </button>
            <label class="layui-form-label">配送方式</label>
            <div class="layui-input-inline">
                <select name="mode_distribution" id="mode_distribution">
                    <option value="线上配送">线上配送</option>
                    <option selected="selected" value="到店取货">到店取货</option>
                </select>
            </div>
            <div class="layui-input-inline">
                <div class="layui-input-block">
                    <input type="tel" name="phone" lay-verify="required|phone" autocomplete="off"
                           class="layui-input" id="phone" placeholder="请输入联系电话">
                </div>
            </div>
            <div class="layui-input-block layui-col-md4">
                <div class="layui-input-block">
                    <input type="tel" name="address" lay-verify="" autocomplete="off" id="address" readonly="readonly"
                           class="layui-input address" placeholder="请输入地址">
                </div>
            </div>
        </div>
    </div>
</div>
<div class="layui-form">
    <table class="layui-table">
        <colgroup>
            <col width="150">
            <col width="150">
            <col width="200">
            <col>
        </colgroup>
        <thead>
        <tr>
            <th>商品id</th>
            <th>商品名</th>
            <th>单价(元)</th>
            <th>数量</th>
            <th>总价(元)</th>
        </tr>
        </thead>
        <tbody id="goodsList">
        <tr id="hj">
            <td>合计</td>
            <td></td>
            <td></td>
            <td></td>
            <td id="totalPrice"></td>
        </tr>
        </tbody>
    </table>
</div>
</div>
<script src="/layui/layui.all.js"></script>
<script>
    layui.use(['element', 'layer', 'form'], function () {
        var table = layui.table;
        var element = layui.element;
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var templateHtml = '<tr class="oneGoods">' +
            '                <td class="goodsId">#GOODSID#</td>' +
            '                <td class="name">#NAME#</td>' +
            '                <td class="price">#PRICE#</td>' +
            '                <td class="goodsCount" id="count_#NUMBER#">#COUNT#</td>' +
            '                <td class="goodsTotal" id="total_#NUMBER#">#TOTAL#</td>' +
            '            </tr>';

        /**
         * 获取商品
         * 生产随机数代表一个商品
         */
        function getGoods() {
            var currentGoods;
            var url = '/goods/getGoods';
            var number = 1;
            $.ajax({
                url: url,
                method: "POST",
                async: false,
                success: function (data) {
                    data = data.data
                    console.log(data);
                    if (data) {
                        number = Math.round(Math.random() * data.length);
                        currentGoods = data[number];
                        // console.log("currentGoods:",currentGoods)
                    }
                }
            })
            return currentGoods;
        }

        var totalPrice = 0;

        /**
         * 添加的商品
         */
        var goodsObj = {};


        /**
         * 添加地址事件
         */
        $('#addAddress').on('click', function () {
            layer.open({
                type: 2,
                skin: 'my_popup1',
                area: ['95%', '90%'],
                anim: 2,
                maxmin: true,
                title: "<a>配送地址</a>",
                content: ['/mapJump/searchMap', 'no'],
                //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                end: function () {
                    $('#address').val(localStorage.getItem("address"))
                    localStorage.setItem("address",'')
                }
            });
        })
        /**
         * 添加商品的点击事件
         */
        $('#add').on('click', function () {
            var data = getGoods();//商品
            console.log("data", data);
            var id = data.id;//商品id
            var price = data.goods_price;
            totalPrice += price;
            var currentGoodObj = goodsObj[id];//
            console.log("currentGoodObj:", currentGoodObj);
            console.log("goodsObj:", goodsObj);
            var obj = {
                count: currentGoodObj ? ++currentGoodObj.count : 1,
                total: currentGoodObj ? currentGoodObj.count * price : price
            };
            console.log("obj:", obj);
            if (currentGoodObj) {
                $("#count_" + id).html(obj.count);
                $("#total_" + id).html(obj.total);
            } else {
                var html = templateHtml.replace("#GOODSID#", id)
                    .replace("#NAME#", data.goods_name)
                    .replace("#PRICE#", data.goods_price)
                    .replace("#COUNT#", obj.count)
                    .replace("#NUMBER#", id)
                    .replace("#NUMBER#", id)
                    .replace("#TOTAL#", obj.total);
                // $('#goodsList').append(html);
                $('#hj').before(html);
                goodsObj[id] = obj;
            }
            $('#totalPrice').html(totalPrice);
        })
        /**
         * 点击确定添加订单的事件
         */
        $('#addOrder').on('click', function () {
            //获取表的数据
            var regex = '^/1\\d{10}/$'
            var tableData = getTableData();
            if ($('#mode_distribution').val() == '线上配送') {

                if ($('#phone').val() == null || $('#phone').val() == '') {
                    layer.msg("线上配送,联系电话不能为空");
                    return;
                } else {
                    if (!(/^(1[3-9]){1}\d{9}$/.test($('#phone').val()))) {
                        layer.msg("电话号码有误,请检查电话号码");
                        return;
                    }
                }
                if ($('#address').val() == null || $('#address').val() == '') {
                    layer.msg("线上配送,配送地址不能为空");
                    return;
                }
            }
            $.ajax({
                url: '/goodsOrder/addOrders',
                method: "POST",
                data: {
                    'data': JSON.stringify(tableData)
                },
                async: false,
                success: function (data) {
                    totalPrice = 0;
                    $('#goodsList').html('<tr id="hj">' +
                        '                <td>合计</td>' +
                        '                <td></td>' +
                        '                <td></td>' +
                        '                <td></td>' +
                        '                <td id="totalPrice"></td>' +
                        '            </tr>');
                    $('#phone').val('');
                    $('#address').val('');
                    layer.msg(data.msg);
                },
                error: function (data) {
                    layer.msg('添加订单失败');
                }
            })
        })

        /**
         * 加载订单的数据
         */
        function getTableData() {
            //如果配送方式为线上配送
            var order_status = 4;
            var phone = null;
            var address = null;
            if ($('#mode_distribution').val() == '线上配送') {
                phone = $('#phone').val();
                address = $('#address').val();
                order_status = 1;
            }
            var tr = $('.oneGoods');
            var goodsList = [];
            for (var row = 0; row < tr.length; row++) {
                var goods = {};
                var td = $(tr[row]).children();
                goods.goods_id = $(td[0]).html();
                goods.goods_count = $(td[3]).html();
                goods.order_price = totalPrice;
                goods.order_status = order_status;
                goods.address = address;
                goods.phone = phone;
                goodsList.push(goods);
            }
            console.log('goodsList', goodsList)
            return goodsList
        }
    })
</script>
</body>
</html>